"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : DMS分布式锁
Case Name   : 备节点已获取S锁，主节点开启事务执行delete，关闭S锁，备节点查询表数据
Create At   : 2023/4/24
Owner       : opentestcase033
Description :
    1.创建测试表
    2.备节点开启事务A获取S锁，回滚
    3.主节点执行delete
    4.备节点查询表数据
    5.清理环境
Expect:
    1.成功
    2.执行成功，获取锁
    3.阻塞，事务A回滚后执行成功
    4.成功，1条数据
    5.成功
History     :
"""

import os
import time
import unittest

from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.ComThread import ComThread


class DmsOck(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.std_sh = CommonSH('Standby1DbUser')
        self.constant = Constant()
        self.table = 't_dms_ock_0041'

    def test_dms_ock(self):
        text1 = '-----step1:创建测试表;expect:成功-----'
        self.log.info(text1)
        create_tb = \
            f"drop table if exists {self.table} cascade;" \
            f"create table {self.table}(" \
            f"id int, name varchar, source number) with (segment = on);" \
            f"insert into {self.table} values(1,'haha',92),(2,'tutu',85);"
        create_res = self.pri_sh.execut_db_sql(create_tb)
        self.log.info(create_res)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, create_res,
                      f"执行失败:{text1}")
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, create_res,
                      f"insert失败:{text1}")

        text2 = '-----step2:备节点开启事务A获取X锁，回滚;expect:执行成功-----'
        self.log.info(text2)
        sql_a = f'''begin;
        select * from {self.table};
        select pg_sleep(3);
        rollback;'''
        self.log.info(sql_a)
        session1 = ComThread(self.std_sh.execut_db_sql, args=(sql_a,))
        session1.setDaemon(True)
        session1.start()
        time.sleep(1)

        text3 = '-----step3:主节点执行delete;expect:执行成功-----'
        self.log.info(text3)
        delete_res = self.pri_sh.execut_db_sql(
            f"delete from {self.table} where name = 'haha';")
        self.log.info(delete_res)
        self.assertIn(self.constant.DELETE_SUCCESS_MSG, delete_res,
                      f"执行失败:{text3}")
        session1.join(10)
        res = session1.get_result()
        self.log.info(f'session1_results: {res}')
        self.assertIn('1 | haha |     92', res, f"执行失败:{text2}")
        self.assertIn('2 | tutu |     85', res, f"执行失败:{text2}")
        self.assertIn(self.constant.ROLLBACK_MSG, res, f"执行失败: {text2}")

        text4 = '-----step4:备节点查询表数据;expect:1条数据-----'
        self.log.info(text4)
        select_res = self.std_sh.execut_db_sql(f'select * from {self.table};')
        self.log.info(select_res)
        self.assertIn('2 | tutu |     85', select_res, f"执行失败:{text3}")
        self.assertIn('1 row', select_res, f"执行失败:{text3}")

    def tearDown(self):
        text5 = '-----step5:清理环境 expect:成功-----'
        self.log.info(text5)
        drop_tb_res = self.pri_sh.execut_db_sql(
            f"drop table {self.table} cascade;")
        self.log.info(drop_tb_res)
        self.assertIn(self.constant.DROP_TABLE_SUCCESS,
                      drop_tb_res, f"删表失败:{text5}")
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
